package org.jeecg.modules.demo.hd.controller;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.zhyd.oauth.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.vo.RequestVo;
import org.jeecg.modules.demo.hd.entity.AppMyProject;
import org.jeecg.modules.demo.hd.entity.AppMyProjectClickdetail;
import org.jeecg.modules.demo.hd.entity.AppProject;
import org.jeecg.modules.demo.hd.entity.AppSpace;
import org.jeecg.modules.demo.hd.service.IAppMyProjectClickdetailService;
import org.jeecg.modules.demo.hd.service.IAppMyProjectService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.hd.service.IAppProjectService;
import org.jeecg.modules.demo.hd.service.IAppSpaceService;
import org.jeecg.modules.demo.hd.vo.myProject.MyProjectModelVo;
import org.jeewx.api.core.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 我的项目
 * @Author: jeecg-boot
 * @Date: 2025-04-16
 * @Version: V1.0
 */
@Api(tags = "我的项目")
@RestController
@RequestMapping("/hd/appMyProject")
@Slf4j
public class AppMyProjectController extends JeecgController<AppMyProject, IAppMyProjectService> {
    @Autowired
    private IAppMyProjectService appMyProjectService;

    @Autowired
    private IAppProjectService projectService;

    @Autowired
    private IAppSpaceService spaceService;

    @Autowired
    private IAppMyProjectClickdetailService projectClickdetailService;

    /**
     * 我的项目列表（后台管理，获取所有）
     *
     * @param appMyProject
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "我的项目列表（后台管理，获取所有）", notes = "我的项目列表（后台管理，获取所有）")
    @GetMapping(value = "/list")
    public Result<IPage<AppMyProject>> queryPageList(AppMyProject appMyProject,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<AppMyProject> queryWrapper = QueryGenerator.initQueryWrapper(appMyProject, req.getParameterMap());
        Page<AppMyProject> page = new Page<AppMyProject>(pageNo, pageSize);
        IPage<AppMyProject> pageList = appMyProjectService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @ApiOperation(value = "我的项目列表", notes = "我的项目列表")
    @GetMapping(value = "/myList")
    public Result<List<MyProjectModelVo>> queryMyList(HttpServletRequest req) {
//        RequestVo requestVo = HttpServletRequestUtil.getRequestVo(req);
        //TODO 记录设备硬件信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<MyProjectModelVo> data = appMyProjectService.getMyProjectList(sysUser.getId());

        // 获取所有奖励广告和广告位状态为0的广告
        List<AppSpace> spaceList = spaceService.getList().stream().
                filter(x -> x.getSpaceType().equals(0) && x.getSpaceState().equals(0)).collect(Collectors.toList());
        if (data.size() == 0) {
            // 查询所有的项目，加入项目
            List<AppProject> list = projectService.list();
            for (AppProject appProject : list) {
                addProject(appProject.getId().toString());
            }
            data = appMyProjectService.getMyProjectList(sysUser.getId());
        }
        data.forEach(item -> {
            // 附上广告位ID
            if (spaceList != null && spaceList.size() > 0) {
                Collections.shuffle(spaceList); // 这会改变list的顺序，但不会影响后续的操作。
                item.setSpaceId(spaceList.get(0).getSpaceId());
            } else {
                item.setSpaceId("103437211");
            }
            // 附上完成点击次数
            item.setAlreadyClickCount(getUserProjectClickCount(sysUser.getId(), item.getId()));
            item.setInterval(3);
        });
        return Result.OK(data);
    }

    private String addProject(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            return "传入参数异常！";
        }
        AppMyProject model = new AppMyProject();
        String projectId2 = projectId;
        AppProject project1 = projectService.getById(projectId2);
        if (ObjectUtils.isEmpty(project1)) {
            return "添加失败！未找到项目！projectId：" + projectId2;
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 需要判断是否已经存在项目
        LambdaQueryWrapper<AppMyProject> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(AppMyProject::getUserId, sysUser.getId());
        List<AppMyProject> myProjects = appMyProjectService.list(lambdaQueryWrapper);
        if (myProjects != null && myProjects.size() > 10) {
            return "添加失败！单用户最多可领取10个项目！";
        }
        long count = myProjects.stream().filter(x -> x.getProjectId().equals(projectId2)).count();
        if (count > 0) {
            return "添加失败！已经领取项目！";
        }
        if (ObjectUtils.isNotNull(project1)) {
            model.setProjectId(projectId2);
            model.setCompletionDays(0);
            model.setIsEnd(0);
            model.setMinValue(0d);
            model.setStartTime(DateUtils.getDateTime());
            model.setUserId(sysUser.getId());
            appMyProjectService.save(model);
        }
        return "";
    }

    /**
     * 通过id查询我的项目
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取我的项目信息", notes = "获取我的项目信息")
    @GetMapping(value = "/queryById")
    public Result<MyProjectModelVo> queryById(@RequestParam(name = "id", required = true) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<AppMyProject> myProjectWrapper = Wrappers.lambdaQuery();
        myProjectWrapper.eq(AppMyProject::getProjectId, id).eq(AppMyProject::getUserId, sysUser.getId());
        AppMyProject appMyProject = appMyProjectService.getOne(myProjectWrapper);
        if (appMyProject == null) {
            return Result.error("未找到对应数据");
        }
        MyProjectModelVo vo = new MyProjectModelVo();
        vo.setAlreadyClickCount(getUserProjectClickCount(sysUser.getId(), id));
        AppProject project1 = projectService.getById(id);
        vo.setClickCount(project1.getCycle());
        vo.setCycle(project1.getCycle());
        vo.setId(project1.getId());
        vo.setImg(project1.getImg());
        vo.setName(project1.getName());
        // 获取所有奖励广告和广告位状态为0的广告
        List<AppSpace> spaceList = spaceService.list().stream().
                filter(x -> x.getSpaceType().equals(0) && x.getSpaceState().equals(0)).collect(Collectors.toList());
        if (spaceList != null && spaceList.size() > 0) {
            Collections.shuffle(spaceList); // 这会改变list的顺序，但不会影响后续的操作。
            vo.setSpaceId(spaceList.get(0).getSpaceId());
        } else {
            vo.setSpaceId("103437211");
        }
        vo.setInterval(3);
        return Result.OK(vo);
    }

    /**
     * 查询用户项目点击次数
     *
     * @param userId
     * @param projectId
     * @return
     */
    private Integer getUserProjectClickCount(String userId, String projectId) {
        // 查询用户和项目，当天点击的次数。
        LambdaQueryWrapper<AppMyProjectClickdetail> queryWrapper = Wrappers.lambdaQuery();
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        queryWrapper.between(AppMyProjectClickdetail::getCreateTime, startOfDay, endOfDay);
        queryWrapper.eq(AppMyProjectClickdetail::getUserId, userId)
                .eq(AppMyProjectClickdetail::getProjectId, projectId);
        int size = projectClickdetailService.list(queryWrapper).size();
        return size;
    }
}
